define(
	[
		'require'
	],
	function(require){
		var st = 0;
		function dateCellFormatter(args, column){
			if (args.row.type & $.wijmo.wijgrid.rowType.data) {
				var data = args.row.data,
					dataKey = column.dataKey,
					formatedTime = APM.util.formatDate(data[dataKey], "yyyy-MM-dd H:mm");
				data["_formatted_"+dataKey] = formatedTime;
				args.$container.append(formatedTime);
				return true;
			}
		}
		var Controller = Ember.Controller.extend({
			needs: ["businessDetail"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			pinTimePoint: Ember.computed.alias('controllers.businessDetail.pinTimePoint'),

			businessIdChange: Ember.observer("business.id", function(){
				this.set('keyWord', '');
			}),

			dialogClose:function(){
				$(".application-main").css({
					'margin-top':'0'
				});

				setTimeout(function(){
					$(".application-main").scrollTop(st).css({
						'margin-top':'55px'
					});
				});
			},

			initTime: function(){
		        var ctrl = this;
		        var startDate = ctrl.get("startDate");
		        var endDate = ctrl.get("endDate");
		        if(this.get("clickTimePoint") != null ){
		        	var date = new Date(this.get("clickTimePoint"));
		        	ctrl.set("endDate",new Date(+date+60000));
		        	if((isNaN(startDate))){
		        		ctrl.set("startDate",new Date(+date+60000)-60000);
		        	}else{
		        		ctrl.set("startDate",new Date(+date+60000)-(Math.abs(+endDate-(+startDate))));
		        	}
		        	
		        	
		        	setTimeout(function(){
		        		var startDate = APM.util.formatDate(new Date(+ctrl.get("startDate")), "yyyy/MM/dd H:mm");
		        		var endDate = APM.util.formatDate(new Date(+ctrl.get("endDate")), "yyyy/MM/dd H:mm");
		        		$('#config-demo').val(startDate+' - '+endDate);
		        	});
		        	
		        }else{
		        	var sdate = new Date(new Date() - timeD_value - 60000-60000);
			        sdate.setSeconds(0);
			        sdate.setMilliseconds(0); 
			        ctrl.set("startDate",new Date(+sdate));
			        var edate = new Date(new Date() - timeD_value-60000);
			        edate.setSeconds(0);
			        edate.setMilliseconds(0); 
			        ctrl.set("endDate",new Date(+edate));
		        }
		    },
			clickTimePoint: Ember.computed.oneWay('controllers.businessDetail.clickTimePoint'),
			/*
				列配置
			*/
			perfColumns: [
				{
					headerText: "第一次出现时间",
					dataKey:"firstTime",
					width:"14%",
					cellFormatter: dateCellFormatter
				},
				{
					headerText: "最后一次出现时间",
					dataKey:"lastTime",
					width:"14%",
					cellFormatter: dateCellFormatter
				},
				{
					headerText: "请求标识",
					dataKey:"uri",
					textAlignment:"left",
					width:350,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var value = args.row.data.uri;

							args.$container
								.attr("title",value)
								.addClass("btn-link")
								.css({"overflow": "hidden","white-space": "nowrap","text-overflow": "ellipsis","width":"350px","text-align":"center"})
								.append(APM.util.escape(value));
							return true;
						}
					}
				},
				{
					headerText: "错误码",
					dataKey:"responseCode",
					width:"10%",
				},
				{
					headerText: "错误信息",
					dataKey:"errorMessage",
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data;
							var value = data.errorMessage;

							var $item = $('<div class=""></div>').appendTo(args.$container);
							$item.html(APM.util.escape(value));
							args.$container.attr("title",value);

							return true;
						}
					}
				},
				{
					headerText: "出现次数",
					dataKey:"repeatCount",
					width:"10%",
				}
			],

			errorcodes: Ember.A(),

			pageSize: 10,

			keyUpEnent: function(){
				var ctrl = this;
				setTimeout(function(){
					$("#mouseKeyUp").on("keyup",function(event){
						if(event.keyCode == 13){
							ctrl.requireData();
						};
					});
				},0)
				
			},

			requireData: function(){
				var ctrl = this;
				var params = {
					appId: this.get("business.id"),
					nodeId: this.get("model.id"),
					keyWord: this.get("keyWord"),
					pageIndex: this.get("pageIndex"),
					startDate: +this.get("startDate"),
					endDate: +this.get("endDate")
				};

				if( isLocalDebugModel ){
					params = undefined;
				}

				return this.store.ajax("GET", "node/errors", params)
				.then(function(response){
					var result = Ember.A(response.result);
					var performances = Ember.A(response['result']);
					
					if (performances.length == 0) {
						ctrl.set("pageIndex",0);
						ctrl.set("pageSize",10);
						ctrl.set("totalRows",0);
					} else {
						ctrl.set("pageIndex",response.meta.pageIndex);
						ctrl.set("pageSize",response.meta.pageSize);
						ctrl.set("totalRows",response.meta.total);
					}
					ctrl.set("errorcodes",result);
					
					return response;
				});
			},

			actions: {
				search: function() {
					this.set("pageIndex", 0);
					this.requireData();
				},

				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);

					this.requireData();
				},

				errorGridClicked: function(e, args, view){
					var ctrl = this,
						row = args.cell.row(),
						column = args.cell.column();
					st = $(".application-main").scrollTop();
					if (row.type & $.wijmo.wijgrid.rowType.data) {
						if(column.dataKey == "uri"){
							ctrl.set('tradeId',row.data.rsourceId);
							this.set("curError", row.data);
							this.requireErrorStack(row.data);
							var view = Broada.getView("businessNodeDetailErrorcodeStackDialog");
							var o = view.$()[0];
							if(document.all){
								o.style.filter = "Alpha(Opacity=0)";
							}else{
								o.style.opacity = 0;
							} 
							view.openDialog();


							var i=0;
						    function change(){
						        i = i + 2;
						        if(document.all) o.style.filter = "Alpha(Opacity=" + i + ")";
						        else o.style.opacity = i/100;
						        if(i>100) clearInterval(timer);
						    }
						    var timer = window.setInterval(change,10);
						}
					}
				},

				timePointChange: function(timeRange){
					this.set("startDate",timeRange.startDate);
					this.set("endDate",timeRange.endDate);
					this.requireData();
				},

				timeRangesChange: function(timeRange){
					var ctrl = this;
					var pinTimePoint = ctrl.get("controllers.businessDetail").pinTimePoint;

						ctrl.set("startDate", timeRange.startDate);
						ctrl.set("endDate", timeRange.endDate);
			
					
					var view = Broada.getView("businessTimeRangesTopo");
					if(ctrl.get("pinTimePoint") != timeRange.startDate){
						ctrl.set("pinTimePoint", null);
					}

					/*if(timeRange.selectVal == "n1M"||timeRange.selectVal == "n1d"){
						ctrl.set("startDate", timeRange.startDate);
						ctrl.set("endDate", timeRange.endDate);
					};*/

					ctrl.set("pageIndex", 0);
					ctrl.requireData();
				}
			}
		});

		Controller.reopen({
			curErrorStack: Ember.computed(function(key, value){
				if(arguments.length == 2){
					if(!value._isLoaded){
						this.requireErrorStackDetail(value);
					}else{
						return value;
					}
				}
			}),

			requireErrorStack: function(error){
				var ctrl = this;

				var params = {
					appId: this.get("business.id"),
					nodeId: this.get("model.id"),
					uri: error.uri,
					errorCode: error.dimensionId,//errorCode做了转换
					startDate: +this.get("startDate"),
					endDate: +this.get("endDate")
				};

				if( isLocalDebugModel ){
					params = undefined;
				}

				this.store.ajax("GET", "node/error/stack", params)
				.then(function(response){
					var errorStacks = Ember.A();
					if(!response.result[0]){
						ctrl.set("curErrorStack", {});
						return;
					}
					Ember.A(response.result).forEach(function(item, i){
						errorStacks.push({
							_index: i+1,
							_isLoaded: false,
							id: item.errorId,
							_formattedTime:APM.util.formatDate(item.timestamp, "yyyy-MM-dd H:mm"),
							errorMessage:error.errorMessage
						});
					});
					ctrl.set("errorStacks", errorStacks);
					ctrl.set("curErrorStack", errorStacks[0]);
					return response;
				});
			},

			requireErrorStackDetail: function(error){
				var ctrl = this;
				var params = {
					appId: this.get("business.id"),
					nodeId: this.get("model.id"),
					startDate: +this.get("startDate"),
					endDate: +this.get("endDate")
				};

				if( isLocalDebugModel ){
					params = undefined;
				}

				this.store.ajax("GET", "node/error/stack/"+(isLocalDebugModel?1:error.id), params)
				.then(function(response){
					var errorStack = response.result;
					errorStack._index = error._index;
					errorStack._isLoaded = true;
					errorStack._formattedTime = error._formattedTime;
					errorStack.errorMessage = error.errorMessage;
					Ember.A(errorStack.fields);
					ctrl.set("curErrorStack", errorStack);
					ctrl.get("errorStacks")[errorStack._index-1] = errorStack;
					return response;
				});
			},

			actions: {
				gotoErrorStack: function(index){
					var cur = this.get("curErrorStack"),
						all = this.get("errorStacks"),
						len = all.length;
					function display(){
						var view = Broada.getView("businessNodeDetailErrorcodeStackDialog");
							var o = view.$()[0];
							if(document.all){
								o.style.filter = "Alpha(Opacity=0)";
							}else{
								o.style.opacity = 0;
							} 
							var i=0;
						    function change(){
						        i = i + 2;
						        if(document.all) o.style.filter = "Alpha(Opacity=" + i + ")";
						        else o.style.opacity = i/100;
						        if(i>100) clearInterval(timer);
						    }
						    var timer = window.setInterval(change,10);
					}
					switch(index){
						case "first":
							display();
							this.set("curErrorStack", all[0]);
							break;
						case "last":
							display();
							this.set("curErrorStack", all[len-1]);
							break;
						case "+1":
							display();	
							this.set("curErrorStack", all[Math.min(cur._index, len-1)]);
							break;
						case "-1":
							display();
							this.set("curErrorStack", all[Math.max(cur._index-2, 0)]);
							break;
						default:
							display();
							var i = parseInt(index);
							if(!isNaN(i)){
								this.set("curErrorStack", all[Math.min(Math.max(i, 0), len-1)]);
							}
							break;
					}
				}
			}
		});

		APM.BusinessDetailNodedetailErrorcodeController = Controller;
		return Controller;
	}
);